package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.RedisConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmSensitivePageReqDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.WmSensitiveservice;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
@Transactional
@Slf4j
public class WmSensitiveserviceImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive> implements WmSensitiveservice {

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    @Autowired
    private CacheService cacheService;

    /**
     * 保存、修改敏感词
     *
     * @param wmSensitive
     */
    @Override
    public void updateOrSave(WmSensitive wmSensitive) {
        //校验
        if(wmSensitive == null || StringUtils.isBlank(wmSensitive.getSensitives())){
            throw new RuntimeException("参数有误");
        }
        //保存、修改
        if(wmSensitive.getId() == null){
            //保存
            //设置数据
            wmSensitive.setCreatedTime(new Date());

            //保存
            save(wmSensitive);
        }else {
            updateById(wmSensitive);
        }
        //删除缓存
        cacheService.delete(RedisConstants.SENSITIVE_CACHE_KEY);

    }

    /**
     * 查询敏感词列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findList(WmSensitivePageReqDto dto) {
        //校验
        dto.checkParam();

        //分页条件查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmSensitive> lqw = new LambdaQueryWrapper<>();

        //关键字模糊查询
        if (StringUtils.isNotBlank(dto.getName())) {
            lqw.like(WmSensitive::getSensitives,dto.getName());
        }
        //查询
        IPage selectPage = wmSensitiveMapper.selectPage(page, lqw);

        //结果返回
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),(int)selectPage.getTotal());
        result.setData(selectPage.getRecords());
        return result;
    }

    /**
     * 删除敏感词
     *
     * @param id
     */
    @Override
    public void delSensitive(Integer id) {
        wmSensitiveMapper.deleteById(id);
        //删除缓存
        cacheService.delete(RedisConstants.SENSITIVE_CACHE_KEY);

    }
}
